package com.ruoyi.feike.instener;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.EmailUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.feike.domain.*;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.IDealercodeContractFilingService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Component
public class CancelSendMailListener implements ExecutionListener , ApplicationContextAware {

    private Expression state;

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; //  发送发邮箱地址

    @Value("${uat.url}") // 从application.yml配置文件中获取
    private String url; //  网址

    @Value("${uat.msg}") // 从application.yml配置文件中获取
    private String msg; //  网址

    @Value("${uat.isSendEmal}") // 从application.yml配置文件中获取
    private String isSendEmal; //  网址

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    private static ApplicationContext context = null;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        log.info("开始发办结邮件");
        ArrayList<String> userNames = new ArrayList<>();
        userNames.add(SecurityUtils.getUsername());
        ArrayList<SysUser> users = new ArrayList<>();
        String activeProfile = context.getEnvironment().getActiveProfiles()[0];
        if(activeProfile.equals("dev")){
            isSendEmal = "true";
            url = "http://localhost:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }else if(activeProfile.equals("prod")){
            isSendEmal = "true";
            url = "http://10.226.185.146:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="";
        }else if (activeProfile.equals("uat")){
            isSendEmal = "true";
            url = "http://10.226.186.143:82";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }
        //需要更新状态
        String businessKey =null ;
        String instanceId = delegateExecution.getProcessInstanceId();
        if(null !=instanceId){
            HistoryService historyService = SpringUtils.getBean(HistoryService.class);
            ISysUserService userService = SpringUtils.getBean(ISysUserService.class);
            List<HistoricTaskInstance> taskInstance = historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceId).list();
            HistoricProcessInstance procInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
            businessKey = procInstance.getBusinessKey();

            ContractRecordMapper contractRecordMapper = SpringUtils.getBean(ContractRecordMapper.class);
            DealercodeContractFilingMapper dealercodeContractFilingMapper = SpringUtils.getBean(DealercodeContractFilingMapper.class);
            IAnnualReviewyService annualReviewyService = SpringUtils.getBean(IAnnualReviewyService.class);
            AnnualReviewyMapper mapper = SpringUtils.getBean(AnnualReviewyMapper.class);

            AnnualReviewy annualReviewy = mapper.selectAnnualReviewyByInstanceId(businessKey);

            if(annualReviewy !=null  && annualReviewy.getDealerName() !=null && annualReviewy.getSector() !=null && annualReviewy.getLimitType()!=null) {
                String[] split = businessKey.split("-");
                ContractRecord newContractRecord = new ContractRecord();
                newContractRecord.setInstanceid(split[0]);
                newContractRecord.setDealername(annualReviewy.getDealerName());
                newContractRecord.setSector(annualReviewy.getSector());
                newContractRecord.setLimitType(annualReviewy.getLimitType());
                List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(newContractRecord);
                for (ContractRecord contractRecord : contractRecords) {
                    contractRecord.setStatus("作废");
                    contractRecordMapper.updateContractRecord(contractRecord);
                }
                DealercodeContractFiling newDealercodeContractFiling = new DealercodeContractFiling();
                newDealercodeContractFiling.setSubProcessId(businessKey);
                newDealercodeContractFiling.setInstanceId(split[0]);
                newDealercodeContractFiling.setDealerNameCN(annualReviewy.getDealerName());
                newDealercodeContractFiling.setSector(annualReviewy.getSector());
                newDealercodeContractFiling.setLimitType(annualReviewy.getLimitType());
                List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(newDealercodeContractFiling);
                for (DealercodeContractFiling dealercodeContractFiling : dealercodeContractFilings) {
                    dealercodeContractFiling.setStatus("1");
                    dealercodeContractFilingMapper.updateDealercodeContractFiling(dealercodeContractFiling);
                }
                List<String> workflowFormData = annualReviewyService.getWorkflowFormData(split[0]);
                userNames.add(annualReviewy.getCreateBy());
                for (String account : workflowFormData) {
                    userNames.add(account);
                }
                LinkedHashSet<String> hashSet = new LinkedHashSet<>(userNames);
                ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);
                System.out.println("邮件接收人:"+listWithoutDuplicates);
                for (String listWithoutDuplicate : listWithoutDuplicates) {
                    SysUser sysUser = userService.selectUserByUserName(listWithoutDuplicate);
                    if(sysUser != null && sysUser.getEmail()!=null){
                        users.add(sysUser);
                    }
                }

            }
            //保险变更
            if(annualReviewy !=null &&  annualReviewy.getType()!=null && annualReviewy.getType().equals("InsuranceChange")) {
                annualReviewy.setState("8");
                SpringUtils.getBean(IAnnualReviewyService.class).updateAnnualReviewyByInstanceId(annualReviewy);
                NewSumKeepMapper newSumKeepMapper = SpringUtils.getBean(NewSumKeepMapper.class);

                HNewSumKeepModifyMapper bean = SpringUtils.getBean(HNewSumKeepModifyMapper.class);

                List<HNewSumKeepModify> hNewSumKeepModifies = bean.selectHNewSumKeepModifyListByInstanceId(annualReviewy.getInstanceId());
                for (HNewSumKeepModify newSumKeepModify : hNewSumKeepModifies) {
                    NewSumKeep newSumKeep = newSumKeepMapper.selectNewSumKeepById(newSumKeepModify.getOldid());
                    newSumKeep.setInTransition(1);
                    newSumKeepMapper.updateNewSumKeep(newSumKeep);
                }

            }

            //保险变更
            if(annualReviewy !=null &&  annualReviewy.getType()!=null && annualReviewy.getType().equals("WFSLimitSetUp_1")) {
                annualReviewy.setState("7");
                SpringUtils.getBean(IAnnualReviewyService.class).updateAnnualReviewyByInstanceId(annualReviewy);
                //变更报表状态
                ApprovalStatusReportMapper approvalStatusReportMapper = SpringUtils.getBean(ApprovalStatusReportMapper.class);
                ApprovalStatusReport approvalStatusReport = new ApprovalStatusReport();
                approvalStatusReport.setInstanceId(businessKey);
                List<ApprovalStatusReport> approvalStatusReports = approvalStatusReportMapper.selectApprovalStatusReportList1(approvalStatusReport);
                if(approvalStatusReports!=null && approvalStatusReports.size()>0){
                    for (ApprovalStatusReport statusReport : approvalStatusReports) {
                        statusReport.setSituation("DM Cancel");
                        statusReport.setCompletedDate(new Date());
                        approvalStatusReportMapper.updateApprovalStatusReport(statusReport);
                    }
                }
                List<String> workflowFormData = annualReviewyService.getWorkflowFormData(businessKey);
                if(workflowFormData!=null && workflowFormData.size()>0){
                    for (String account : workflowFormData) {
                        userNames.add(account);
                    }
                }
                LinkedHashSet<String> hashSet = new LinkedHashSet<>(userNames);
                ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);
                System.out.println("邮件接收人:"+listWithoutDuplicates);
                for (String listWithoutDuplicate : listWithoutDuplicates) {
                    SysUser sysUser = userService.selectUserByUserName(listWithoutDuplicate);
                    if(sysUser != null && sysUser.getEmail()!=null){
                        users.add(sysUser);
                    }
                }

            }
            //判断是否是自发合同
            if(annualReviewy !=null &&  annualReviewy.getType()!=null && annualReviewy.getType().equals("contractApproval")) {
                DealercodeContractFiling newDealercodeContractFiling = new DealercodeContractFiling();
                newDealercodeContractFiling.setSubProcessId(businessKey);
                newDealercodeContractFiling.setInstanceId(businessKey);
                List<DealercodeContractFiling> dealercodeContractFilings = dealercodeContractFilingMapper.selectDealercodeContractFilingList(newDealercodeContractFiling);
                for (DealercodeContractFiling dealercodeContractFiling : dealercodeContractFilings) {
                    dealercodeContractFiling.setStatus("1");
                    dealercodeContractFilingMapper.updateDealercodeContractFiling(dealercodeContractFiling);
                }
                ContractRecord newContractRecord = new ContractRecord();
                newContractRecord.setInstanceid(businessKey);
                List<ContractRecord> contractRecords = contractRecordMapper.selectContractRecordList(newContractRecord);
                for (ContractRecord contractRecord : contractRecords) {
                    contractRecord.setStatus("作废");
                    contractRecordMapper.updateContractRecord(contractRecord);
                }
                List<String> workflowFormData = annualReviewyService.getWorkflowFormData(businessKey);
                userNames.add(annualReviewy.getCreateBy());
                for (String account : workflowFormData) {
                    userNames.add(account);
                }
                LinkedHashSet<String> hashSet = new LinkedHashSet<>(userNames);
                ArrayList<String> listWithoutDuplicates = new ArrayList<>(hashSet);
                System.out.println("邮件接收人:"+listWithoutDuplicates);
                for (String listWithoutDuplicate : listWithoutDuplicates) {
                    SysUser sysUser = userService.selectUserByUserName(listWithoutDuplicate);
                    if(sysUser != null && sysUser.getEmail()!=null){
                        users.add(sysUser);
                    }
                }
            }

        }

        if(isSendEmal!=null && isSendEmal.equals("true") && users.size()>0) {
            for (SysUser user : users) {
                //发送邮件
                sendMailByEmailInfo(user, businessKey);
            }

        }
    }

    public void sendMailByEmailInfo(SysUser user,String instanceId) {
            try {
                AnnualReviewyMapper reviewyMapper = SpringUtils.getBean(AnnualReviewyMapper.class);
                String str = reviewyMapper.selectByInstanceId(instanceId);

                BasicInformationMapper informationMapper = SpringUtils.getBean(BasicInformationMapper.class);
                List<BasicInformation> basicInformations = informationMapper.selectDealerGroupByByInstanceId(instanceId);

                String names = "";
                for (BasicInformation basicInformation : basicInformations) {
                    if(StringUtils.isNotEmpty(basicInformation.getDealerNameCN())){
                        names += basicInformation.getDealerNameCN();
                        continue;
                    }
                }
                String ln = "<br>";
                String content = msg +  ln + "网站链接:"+ "<a href ='" + url + "'>点此登录</a>"+"|--------|申请流程名称："+str+"|----------|经销商名称: "+names;
                // 测试文本邮件发送（无附件）
                String to = user.getEmail();
                if(!StringUtil.isEmpty(to)){
                    System.out.println("发送办结任务到"+ to);
                    String title = "您有任务已作废";
                    //带附件方式调用
                    JavaMailSender bean = SpringUtils.getBean(JavaMailSender.class);
                    new EmailUtil(from, bean).sendMessageCarryFiles(to, title, content, null);
                    // return AjaxResult.success();
                }
            } catch (Exception e) {
               e.printStackTrace();
            }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
